<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input type="text" v-model='uname'/>
    </div>
    <div>
      <span>年龄:</span>
      <input type="number" v-model='Age'/>
    </div>
    <div>
      <span>性别:</span>
      <select v-model="Sex">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click="btn">添加/修改</button>
    </div>
    <div>
      <table
        border="1"
        cellpadding="10"
        cellspacing="0"
      >
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="(item,index) in arr" :key="index">
          <td>{{index + 1}}</td>
          <td>{{item.name}}</td>
          <td>{{item.age}}</td>
          <td>{{item.sex}}</td>
          <td>
            <button @click="fnBtn(index)">删除</button>
            <button @click="funBtn(index)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
export default {
  data(){
    return {
      uname:'',
      Age: '',
      Sex:[],
      index:0,
      falg:false,
      arr:[
        {name: 'Tom',age:19,sex:'男'},
        {name: 'Jone',age:20,sex:'女'},
      ]
    }
  },
  methods:{
    btn(){
      // 判断是否为空
      if(this.uname.trim() === ''|| this.Age === ''|| this.Sex==='')  return alert('不能输入为空,请重新输入！')
      if(this.falg){
        // 如果全局变量为true的时候进行原值的修改操作,反之进行添加操作
       this.arr[this.index].name = this.uname  //this.index 是全局的index,点击编辑以后将当前的那一项index赋值给全局的index
       this.arr[this.index].age = this.Age
       this.arr[this.index].sex = this.Sex
       this.falg =false
      }else {
        this.arr.push({
        name:this.uname,
        age:this.Age,
        sex:this.Sex,
      })
      }
      // 清空操作
      this.uname = ''
      this.Age = ''
      this.Sex = ''
    },
    // 删除操作
    fnBtn(index){
       this.arr.splice(index, 1)
    },
    // 编辑赋值给输入框功能
    funBtn(index){
       this.falg = true
       this.index = index  // 将当前这一项的索引给到全局的index变量
       this.uname = this.arr[index].name
       this.Age = this.arr[index].age
       this.Sex = this.arr[index].sex
    }
  }
}
</script>
